import jwt_decode from "jwt-decode"
import {
  login,
  getUser,
} from '@/api/HttpAutoTestService/user'
import {
  setToken,
  getToken,
  removeToken
} from '@/libs/util'

export default {
  state: {
    id: '',
    username: '',
    token: getToken(),
    access: '',
    hasGetInfo: false,
  },
  mutations: {
    setId(state, id) {
      state.id = id
    },
    setUsername(state, username) {
      state.username = username
    },
    setToken(state, token) {
      state.token = token
    },
    // 菜单路由访问权限
    // setAccess(state, access) {
    //   state.access = access
    // },
    setHasGetInfo(state, status) {
      state.hasGetInfo = status
    },
  },
  getters: {},
  actions: {
    // 登录
    handleLogin({
      commit
    }, {
      username,
      password
    }) {
      username = username.trim()
      password = password.trim()
      return new Promise((resolve, reject) => {
        login({
          username,
          password
        }).then(res => {
          const token = res.data;
          setToken(token)
          commit('setToken', token)
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut({
      state,
      commit
    }) {
      return new Promise((resolve, reject) => {
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        removeToken()
        // 设置菜单路由访问权限为[]
        commit('setId', '')
        commit('setUsername', '')
        commit('setToken', '')
        // commit('setAccess', [])
        commit('setHasGetInfo', false)
        resolve()
      })
    },
    // 获取用户相关信息
    getUser({
      state,
      commit
    }) {
      return new Promise((resolve, reject) => {
        try {
          const token = state.token
          const access_token = token.access
          var decoded = jwt_decode(access_token)
          const user_id = decoded.user_id
          getUser(user_id).then(res => {
            const data = res.data
            commit('setId', data.id)
            commit('setUsername', data.username)
            // 设置菜单路由访问权限
            // commit('setAccess', data.access)
            commit('setHasGetInfo', true)
            resolve(data)
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    }
  }
}
